package com.itheima.interceptor;

import com.google.gson.Gson;
import com.itheima.util.JwtUtils;
import com.itheima.util.UserHolder;
import com.itheima.vo.Result;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component //放到容器里
public class LoginInterceptor implements HandlerInterceptor {


   @Autowired
   private Gson gson;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求头中的令牌(token)
        String token = request.getHeader("token");
        //2.解析toklen，如果解析失败，返回错误结果(未登录)
        try {
            Claims claims = JwtUtils.parseJWT(token);
            Integer empId = (Integer) claims.get("id");

            //将用户存入ThreadLocal
            UserHolder.set(empId);
        }catch (Exception e){
            log.info("token错误");
            //返货错误信息
            String json = gson.toJson(Result.error("NOT_LOGIN"));
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(json);
            return false;//结束判断
        }

        //3.放行
        return true;
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}
